package com.mobimagic.lockscreen;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.mobimagic.lockscreen.sdk.LockScreenSDK;
import com.qihoo360.common.utils.Utils;
import com.qihoo360.mobilesafe.core.ProcessManager;
import com.qihoo360.mobilesafe.opti.sysclear.model.Item;
import com.qihoo360.mobilesafe.support.NativeManager;

public class ClockAppReaderHelper {

    private static ClockAppReaderHelper instance;
    private static final boolean DEBUG = AppEnv.bAppdebug;
    private static final String TAG = "ClockAppReaderHelper";
    private static final int COLOK_CATEGORY = 100;
    private static final int COLOK_FLAG = 4;
    private Handler mIoHandler;
    private Context mContext;
    private long clockV5Time = 0;
    private List<String> mClockLists;

    private ClockAppReaderHelper(Context context) {
        mContext = context;
        mClockLists = new ArrayList<String>();
        HandlerThread handlerThread = new HandlerThread("clockthread");
        handlerThread.start();
        mIoHandler = new Handler(handlerThread.getLooper());
    }

    public synchronized static ClockAppReaderHelper getInstance() {
        if (instance == null) {
            instance = new ClockAppReaderHelper(LockScreenSDK.getInstance().getContext());
        }
        return instance;
    }

    public List<String> getClockList() {
        loadConfig();
        if (DEBUG) {
            synchronized (ClockAppReaderHelper.this) {
                Log.i(TAG, "getClockList==" + mClockLists);
            }
        }
        return mClockLists;
    }

    public void loadConfig() {
        if (DEBUG) {
            Log.d(TAG, "loadConfig");
        }
        mIoHandler.post(new Runnable() {

            @Override
            public void run() {
                InputStream in = Utils.openLatestInputFile(LockScreenSDK.getInstance().getContext(),
                        ProcessManager.BOOSTER_CFG_FILENAME);
                if (in != null) {
                    in = Utils.getDESDecryptInputStream(in, NativeManager.DES_KEY);

                    try {
                        byte[] b = inputStream2Byte(in);
                        String srt2 = new String(b, "UTF-8");
                        JSONObject result = new JSONObject(srt2);
                        synchronized (ClockAppReaderHelper.this) {
                            getList(result.optJSONArray("package_"));
                        }
                        if (DEBUG) {
                            Log.d(TAG, "srt2==" + srt2);
                        }
                    } catch (Exception e) {
                        if (DEBUG)
                            Log.e(TAG, "Failed to load " + ProcessManager.BOOSTER_CFG_FILENAME, e);
                    }

                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (Exception e) {
                        if (DEBUG)
                            Log.e(TAG, "Failed to close " + ProcessManager.BOOSTER_CFG_FILENAME, e);
                    }
                }
                if (DEBUG) {
                    Log.d(TAG, "loadConfig done");
                }
            }
        });
    }

    private void getList(JSONArray array) throws JSONException {
        if (DEBUG) {
            Log.i(TAG, "getList");
        }
        if (array == null || array.length() < 1) {
            return;
        }
        if (mClockLists != null && mClockLists.size() != 0) {
            mClockLists.clear();
        }
        int length = array.length();
        for (int i = 0; i < length; i++) {//遍历JSONArray 
            JSONObject oj = array.optJSONObject(i);
            Item item = getItem(oj);
            if (item.getCategory() == COLOK_CATEGORY && item.getFlag() == COLOK_FLAG) {
                mClockLists.add(item.getName());
            }
        }
    }

    private Item getItem(JSONObject oj) {
        try {
            Item item = new Item();
            item.setName(oj.optString("name"));
            item.setCategory(stringToInt(oj.optString("category")));
            item.setFlag(stringToInt(oj.optString("flag")));
            return item;
        } catch (Exception e) {
            return null;
        }
    }

    private int stringToInt(String str) {
        int vlaue = 0;
        try {
            vlaue = Integer.valueOf(str);
        } catch (Exception e) {
        }
        return vlaue;
    }

    private byte[] inputStream2Byte(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
        } catch (Exception e) {
            if (DEBUG)
                Log.e(TAG, "Failed to load " + ProcessManager.BOOSTER_CFG_FILENAME, e);
        }
        return out.toByteArray();

    }

}

